package medium;

/**
 * @Description : TODO
 * @Author : machong
 * @Date : 2022/3/19 2:17
 * @Version : 1.0
 **/
class leetCode02_addTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //结果
        ListNode result = new ListNode(0);
        //链表指针
        ListNode cursor = result;
        //进位值
        int carry = 0;
        //carry！=0是处理l1和l2为空但进位值仍存在的情况
        while (l1 != null || l2 != null || carry != 0){
            //节点为null就取0
            int l1Val = l1 != null ? l1.val : 0;
            int l2Val = l2 != null ? l2.val : 0;
            int sum = l1Val + l2Val + carry;
            //和除以10取整为进位值
            carry = sum / 10;
            ListNode sumNode = new ListNode(sum % 10);
            //节点的指针后移
            cursor.next = sumNode;
            cursor = sumNode;
            //l1和l2的指针后移
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        return result.next;
    }
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
        }
}

